package websphinx;

import java.util.Vector;



public class MatchCloseRepeat implements MatchAction {
	private String name = null;

	public MatchCloseRepeat(String name) {
		this.name = name;
	}
	@Override
	public boolean match(Matcher matcher) {
		matcher.nextAction = (Integer) matcher.repeats.get(matcher.repeats
				.size() - 1);

		int index = matcher.repeatTimes.size() - 1;
		int repeatTimes = ((Integer) matcher.repeatTimes.get(index));
		repeatTimes++;
		matcher.repeatTimes.set(index, repeatTimes);

		return true;
	}

	@Override
	public boolean apply(Matcher matcher) {
		match(matcher);

		int count = 1;
		int index = matcher.getApplyActions().indexOf(this) - 1;
		for (; index >= 0; index--) {
			if (matcher.getApplyActions().elementAt(index) instanceof MatchGetValue)
				break;
		}

		int repeatTimes = (Integer) matcher.repeatTimes.get(matcher.repeatTimes
				.size() - 1);
		String valueName = ((MatchGetValue) matcher.getApplyActions()
				.get(index)).getName();
		Vector value = (Vector) matcher.data.get(valueName
				+ Integer.toString(repeatTimes + 1));

		if (value == null) {
			matcher.nextAction = matcher.getApplyActions().indexOf(this);
			matcher.repeats.remove(matcher.repeats.size() - 1);
			matcher.repeatTimes.remove(matcher.repeatTimes.size() - 1);
		}

		return true;
	}

}
